package tp.pr4.instructions;

import tp.pr4.Message;
import tp.pr4.NavigationModule;
import tp.pr4.RobotEngine;
import tp.pr4.instructions.exceptions.InstructionExecutionException;
import tp.pr4.instructions.exceptions.WrongInstructionFormatException;
import tp.pr4.items.Item;
import tp.pr4.items.ItemContainer;

public class DropInstruction implements Instruction {

	public DropInstruction() {
		this.s="";
	}
	public DropInstruction(String cad) {
		this.s=cad;
	}

	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		String[] words = cad.split(" ");
		if (words.length != 2) throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
		for (String i : Message.DROP_INSTRUCTION) {
			if (words[0].equalsIgnoreCase(i) )
				return new DropInstruction(words[1]);
		}
		throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
	}

	@Override
	public String getHelp() {
		String help = Message.DROP_INSTRUCTION[0];
		for (int i = 1; i < Message.DROP_INSTRUCTION.length; i++)
			help += "|" + Message.DROP_INSTRUCTION[i];
		help += " <id>";
		return help;
	}

	@Override
	public void configureContext(RobotEngine engine,
			NavigationModule navigation, ItemContainer robotContainer) {
		this.navigation = navigation;
		this.robotContainer = robotContainer;

	}

	@Override
	public void execute() throws InstructionExecutionException {
		Item item = this.robotContainer.getItem(this.s);
		
		if (item == null)
			throw new InstructionExecutionException(Message.NO_ITEM2.replace("<id>", this.s)  + ".");
		else {
			
			if (this.navigation.findItemAtCurrentPlace(this.s)) {
				throw new InstructionExecutionException(Message.NO_ITEM_IN_PLACE.replace("<id>", this.s) );
			} else {
				this.navigation.dropItemAtCurrentPlace(this.robotContainer.pickItem(this.s));
				System.out.println(Message.ITEM_DROPPED.replace("<id>", this.s));
			}
		}

	}

	private NavigationModule navigation;
	private ItemContainer robotContainer;
	String s;
}
